import tkinter as tk
from tkinter import filedialog
import selectSubTime
import threading

# 用于存储线程引用，确保可以在窗口关闭时停止它们
threads = []
stop_event = threading.Event()  # 用于停止线程的事件


def select_folder():
    # 打开文件夹选择对话框
    global folder_path
    folder_path = filedialog.askdirectory(title="选择剧集文件夹")
    if folder_path:
        folder_path_label.config(text=f"剧集文件夹: {folder_path}")

def select_video():
    # 打开文件选择对话框
    global video_path
    video_path = filedialog.askopenfilename(title="选择视频文件")
    if video_path:
        video_path_label.config(text=f"视频文件: {video_path}")

def get_result():
    # 调用 selectSubTime 模块的方法
    if video_path and folder_path:
        stop_event.clear()  # 重置停止标志
        def analyze():
            result_label.config(text=f"结果: {selectSubTime.getresult(video_path, folder_path, result_label)}")
        # threading.Thread(target=analyze).start()
        t = threading.Thread(target=analyze)
        t.daemon = True  # 设置为守护线程，这样主程序退出时，子线程会自动结束
        threads.append(t)
        t.start()
        # result = selectSubTime.getresult(video_path, folder_path, result_label)
        
    else:
        result_label.config(text="请先选择剧集文件夹和视频文件！")

def close_window():
    """在关闭窗口时停止所有线程"""
    # print("关闭窗口，停止所有线程...")
    stop_event.set()  # 通知所有线程停止
    for t in threads:
        t.join(timeout=1)  # 等待线程完成
    root.quit()

# 创建主窗口
root = tk.Tk()
root.title("视频片段查找工具")
root.geometry("400x400")

# 全局变量
folder_path = ""
video_path = ""

# 创建按钮和标签
folder_button = tk.Button(root, text="选择剧集文件夹", command=select_folder)
folder_button.pack(pady=20)

folder_path_label = tk.Label(root, text="未选择剧集文件夹", wraplength=300)
folder_path_label.pack()

video_button = tk.Button(root, text="选择视频文件", command=select_video)
video_button.pack(pady=20)

video_path_label = tk.Label(root, text="未选择视频文件", wraplength=300)
video_path_label.pack()

result_button = tk.Button(root, text="获取结果", command=get_result)
result_button.pack(pady=20)

result_label = tk.Label(root, text="结果将显示在这里", wraplength=300)
result_label.pack()


# 捕捉窗口关闭事件，调用 close_window 函数
root.protocol("WM_DELETE_WINDOW", close_window)
# 运行主循环
root.mainloop()

